// pages/home/index.js
import {getTagData, fnamefixed, userIdParam2, userIdParam, Uint8Array2HexStr, getDatasetData, bytes2long, long2Bytes, checkLogin} from '../../utils/util';
import {TestKeeloq, ENCRYPT, DECRYPT} from '../../utils/keeloq';
import { Web_Socket } from '../../utils/socket';
import { Base64 } from '../../utils/base64';
import { operationCode } from '../../utils/config';

const token123 = "token123";
const password = {second: '23456783', third: '34565644'}
const groups =  [
    { text: '5', value: 1 },
    { text: '10', value: 2},
    { text: '15', value: 3, type: 'warn' },
    { text: '20', value: 4 },
    { text: '30', value: 5 },
    { text: '40', value: 6 },
    { text: '50', value: 7 },
    { text: '60', value: 8 },
    { text: '70', value: 9 },
    { text: '80', value: 10 },
    { text: '90', value: 11 },
    { text: '120', value: 12 },
    { text: '永久', value: 13 },
]
const groupsMap = groupsMap ?? groups.reduce((a, b) => Object.assign(a, {[b.value]: b.text}), {});

const lampsList =  [
    { name: '加密', value: 1 },
    { name: '不加密', value: 0}
]

const formData = {
    available: 3,
    lamps: 1
};
const code = operationCode
const encryt_flag = 0x75 //01110101
const getFilePath = (deviceCode) => `${wx.env.USER_DATA_PATH}/KEY_${deviceCode}.dat`;

const payloadEdun = {placeId: 0};
const payloadCloud = {placeId: 0};
Page({

    /**
     * 页面的初始数据
     */
    data: {
        listEdun: [],
        groupsMap,
        showActionsheet: false,
        groups: groups,
        tabs: [{text: 'E盾'},{text: '云授权'}, {text: '智控密码'}],
        formData,
        groupsText: groupsMap[formData.available],
        placeName: '全部',
        placeNameCloud: '全部',
        lampsList: lampsList
    },

    tapTab: function(e) {
        const {index} = getTagData(e);
        const activeTabIndex = parseInt(index);
        this.setData({activeTabIndex});
    },
    bindDeviceCodeInput: function(e) {
        let {field} = getDatasetData(e)
        field = field.replace(/_(\w)/g, (all, $1) => $1.toUpperCase())
        this.setData({[`formData.${field}`]: e.detail.value})
    },
    tapAvailableCount: function() {
        this.setData({showActionsheet: !0})
    },

    tapPasswordDevice: function() {
        // this.setData({showPasswordActionsheet: true})
    },

    tapEyes: function() {
        this.setData({showPassword: !this.data.showPassword});
    },

    /**action sheet 回调 */
    tapSheetItem: function(e){
        setTimeout(() => {
            this.setData({showActionsheet: !1})
        }, 300);
        const {value} = e.detail
        const {groups} = this.data;
        groups.forEach(g => g.type = g.value === value ? 'warn' : '')
        this.setData({
            ['formData.available']: value,
            groups
        });
    },

    radioChange(e) {
        this.setData({
            ['formData.lamps']: e.detail.value,
        });
    },

    /**分页回调 */
    bindPageList: function(e) {
        const {list, page} = e.detail;
        const {listEdun} = this.data;
        this.setData({listEdun: page === 1 ? list : listEdun.concat(list)});
        this.fixedListEdun(list);
    },

    /**分页回调 */
    bindPageListCloud: function(e) {
      this.setData({selectedAll: false});
        const {list, page} = e.detail;
        // list.forEach(l => l.lockTimeText = new Date(Number(l.lockTime)).Format());
        const {listCloud} = this.data;
        this.setData({listCloud: page === 1 ? list : listCloud.concat(list)});
    },

    /**生成临时密码 */
    async tapGenerate() {
        const {formData} = this.data;
        if (!formData.deviceCode || !/^[A-F0-9]{4}$/.test(formData.deviceCode)) {
            wx.showToast({
              title: '请输入4位设备码(0-9A-F)',
              icon: 'none'
            })
            return false;
        }
        if (!formData.password || !/^[0-9]{6}$/.test(formData.password)) {
            wx.showToast({
              title: '请输入6位联机密码',
              icon: 'none'
            })
            return false;
        }
        try {
            const aRes = await wx.$http.get({url: `/szm/device/encrypt/${formData.deviceCode}/${formData.available}`});
            const pwd_len = (formData.password.length + '').padStart(2, '0');
            const pwd = Array.from(pwd_len + formData.password).map(i => i.charCodeAt(0));
            const temp_lamps = [];
            for (let index = 0; index < 10; index++) {
                temp_lamps.push(48);
            }
            temp_lamps.push(parseInt(formData.lamps) ? 49 : 48)//'1'.charCodeAt() == 49
            const bRes = await wx.$http.get({url: `/szm/device/encryptLinking/${Base64.base64EncArr(pwd.concat(temp_lamps))}`});
            const tempPwd = aRes.data;
            const tempLink = bRes.data;
            const fsm = wx.getFileSystemManager();
            const tempFormData = Object.assign({icPwd: tempPwd + tempLink}, formData)
            const filePath = getFilePath(formData.deviceCode);
            this.setData({
                filePath,
                tempPwd,
                tempLink,
                tempFormData
            })
            fsm.writeFileSync(
                filePath,
                tempPwd + '' + tempLink,
                'utf8'
            )
            console.log({filePath}, tempPwd + '' + tempLink)
        } catch (error) {
            console.error('生成智控密码异常', error)
            wx.showToast({
              title: '生成智控密码异常',
              icon: 'none'
            })
        }
    },

    tapCopy: function() {
        const {tempPwd, formData} = this.data;
        if (!tempPwd) {
            wx.showToast({
              title: '请先生成智控密码',
              icon: 'none'
            })
            return;
        }
        tempPwd && wx.setClipboardData({
          data: `智控密码：${tempPwd}, 可用次数：${groupsMap[formData.available]}`,
        })
        this.saveRecord();
    },

    tapShare: function(){
        wx.shareFileMessage({
            filePath: this.data.filePath,
            success() {},
            fail: console.error,
          })
        this.saveRecord();
    },

    tapRecord: function (params) {
        wx.navigateTo({
          url: './record/record',
        })
    },
     // wx.getFileSystemManager().writeFile({
        //     filePath: path,
        //     data: tempPwd + '',
        //     encoding: 'utf8',
        //     success(res) {
        //       console.log(res)
        //       wx.shareFileMessage({
        //         filePath: path,
        //         success() {},
        //         fail: console.error,
        //       })
        //     },
        //     fail(res) {
        //       console.error(res)
        //     }
        //   })
    //message = {deviceKey: data.dkey}
    postOthers(message) {
        this.setData({showLoading: true})
        const {deviceKey, kvMap} = message;
        Object.keys(kvMap).forEach(i => console.log(`index页面 ${deviceKey}=>请求`, `指令Hex[${parseInt(i).toString(16).toUpperCase().padStart(4, '0')}]`, `值Hex[${Uint8Array2HexStr(kvMap[i], ',')}]`))
        wx.$http.post({url: '/szm/netty/postOthers', data: message}).then(res => {})
    },

    getOnline(message) {
        return wx.$http.post({url: '/szm/netty/online', data: message})
    },

    fixedListEdun(list, index = 0) {
      if(index >= list.length) {
        return;
      }
      setTimeout(() => {
        console.log({index})
        const item = list[index];
        const message = {deviceKey: item.dkey};
        this.getOnline(message).then(res => {
          const {listEdun} = this.data;
          const edun = listEdun.find(le => le.dkey === item.dkey);
          if(edun) {
            edun.online = res.data ? 1 : 0
          }
          this.setData({listEdun})
          const bindingMessage = {
              deviceKey: item.dkey, 
              kvMap: {
                  [code.allStatus]: [0x01],
                  [code.token]: token123
              }
          }
          this.postOthers(bindingMessage);
        });
        this.fixedListEdun(list, index + 1);
      }, 100);
  },

    fixedList2() {
        const {list} = this.data;
        list.forEach(l => {
            const message = {deviceKey: l.dkey};
            setTimeout(() => {
                this.getOnline(message).then(res => {
                    l.online = res.data ? 1 : 0;
                    this.setData({list})
                    const bindingMessage = {
                        deviceKey: l.dkey, 
                        kvMap: {
                            [code.allStatus]: [0x01],
                            [code.token]: token123
                        }
                    }
                    this.postOthers(bindingMessage);
                });
            }, 100);
        })
    },

    [fnamefixed(code.allStatus)](data, deviceKey) {
        // 0x0006：获取联机、绑定、锁定状态
        const {listEdun} = this.data;
        const item = listEdun.find(i => i.dkey === deviceKey);
        if(item) {
            item['binding'] = data[1];
            item['locking'] = data[2];
            this.setData({listEdun});
        }
    },

    socketOnMessage() {
        wx.$eventEmitter.off('index');
        wx.$eventEmitter.on('index', (data) => {
            this.setData({showLoading: false})
            const { kvMap, deviceKey } = data;
            Object.keys(kvMap).forEach(k => {
                const bCode = parseInt(k);
                const fname = fnamefixed(bCode);
                this[fname] && this[fname](kvMap[bCode], deviceKey)
            });
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        // const dnow = Number(1702604879201);
        // console.log(dnow)
        // const bs = long2Bytes(dnow);
        // console.log(bs, dnow === bytes2long(bs))
        // console.log( new Date(Number(bytes2long(bs))).Format('yyyy-MM-dd HH:mm:ss'));
    //         [0, 0, 1, -116, 107, 40, -75, 97]

    },

    getActions: function() {
        wx.$http.get({url: '/szm/place/actionSheet'}).then(res => {
            this.setData({placeActions: res.data})
        });
        wx.$http.get({url: '/szm/room/actionSheet'}).then(res => {
            this.setData({roomActions: res.data})
        });
    },

    tapDevice: function(e) {
        const {id, dkey} = getTagData(e)
        wx.navigateTo({
          url: `./device/device?id=${id}&dkey=${dkey}`,
        })
    },

    tapDeviceCloud: function(e) {
      const {id} = getTagData(e)
      wx.navigateTo({
        url: `./deviceCloud/deviceCloud?id=${id}`,
      })
    },

    tapAdd: function() {
        wx.navigateTo({
          url: './add/add',
        })
    },
    tapProduct: function() {
        wx.navigateTo({
          url: '../product/index',
        })
    },

    initEdun() {
      if(!this.page_edun) {
        this.page_edun = this.selectComponent('#page') 
      }
      this.page_edun.data.limit = 30;
      this.page_edun.data.page = 1;
      if (checkLogin("")) {
          this.setData({isLogin: true});
          this.page_edun.getPageData({url: '/szm/device/page', data: payloadEdun});
          this.getPlaceRoomDTO();
      } else {
        this.setData({isLogin: false});
      }
    },
    initCloud() {
      if(!this.page_cloud) {
        this.page_cloud = this.selectComponent('#pageCloud') 
      }
      this.page_cloud.data.limit = 30;
      this.page_cloud.data.page = 1;
      if (checkLogin("")) {
          this.setData({isLogin: true});
          this.page_cloud.getPageData({url: '/szm/devicecloud/page', data: payloadCloud});
          this.getPlaceRoomDTO();
      } else {
        this.setData({isLogin: false});
      }
    },

    cloudCheckboxChange: function(e) {
      const {value} = e.detail;
      const {listCloud} = this.data;
      listCloud.forEach(l => l.checked = value.includes(l.id.toString()));
      this.setData({
        selectedAll: value.length === listCloud.length,
        listCloud
      });
    },
    cloudSelectAll: function() {
      const {listCloud} = this.data;
      listCloud.forEach(l => l.checked = true);
      this.setData({
        selectedAll: true,
        listCloud
      });
    },
    cloudSelectNone: function() {
      const {listCloud} = this.data;
      listCloud.forEach(l => l.checked = false);
      this.setData({
        selectedAll: false,
        listCloud
      });
    },
    cloudBatchSetting: function() {
      const {listCloud} = this.data;
      const ids = listCloud.filter(l => l.checked).map(l => l.id);
      if(ids.length === 0) {
        wx.showToast({
          title: '请选择设备',
          icon: 'none'
        })
        return;
      }
      wx.navigateTo({
        url: `./batchCloud/batchCloud?ids=${ids.join(",")}`,
      })
    },
    cloudShowBatch: function() {
      this.setData({showBatch: !this.data.showBatch})
    },

    init() {
      Object.assign(payloadEdun, userIdParam());
      Object.assign(payloadCloud, userIdParam());
      Web_Socket.buildSocket('index');
      if(this.data.activeTabIndex === 0) {
        this.initEdun();
      } else if (this.data.activeTabIndex === 1) {
        this.initCloud();
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      const activeTabIndex = Number(wx.getStorageSync('activeTabIndex') || 0);
      this.setData({activeTabIndex})
      this.socketOnMessage();
      
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      const {promise, state} = wx.$wechatLogin;
      console.log({promisestate: state});
      if(state !== "pending") {
        this.init();
      } else {
        promise.then(res => {
          setTimeout(() => {
            this.init();
          }, 1000);
        });
      }
    },
   

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
      wx.setStorageSync('activeTabIndex', this.data.activeTabIndex)
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
      wx.setStorageSync('activeTabIndex', this.data.activeTabIndex)
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
      
    },

    tapGroups: function (e) {
        this.setData({showPlaceActionsheet: true})
    },

    tapPlaceSheetItem: function(e){
        const {placeActions, activeTabIndex} = this.data;
        let {value,index} = e.detail
        this.setData({
            showPlaceActionsheet: false,
        })
        value = parseInt(value);

        if(activeTabIndex === 0) {
          payloadEdun.placeId = value;
          this.setData({
            placeName: placeActions[index].text 
          });
          this.page_edun.data.page = 1;
          this.page_edun.getPageData({url: '/szm/device/page', data: payloadEdun});
        } else if(activeTabIndex === 1) {
          payloadCloud.placeId = value;
          this.setData({
            placeNameCloud: placeActions[index].text 
          });
          this.page_cloud.data.page = 1;
          this.page_cloud.getPageData({url: '/szm/devicecloud/page', data: payloadCloud});
        }
    },

    getPlaceRoomDTO() {
        wx.$http.get({url: '/szm/place/actionSheet'}).then(res => {
            if (res.data && res.data.length > 0) {
                const groups = res.data ? res.data.map(p => {
                    return {
                        text: p.name,
                        value: p.id
                    }
                }) : [];
                groups.unshift({text: '全部', value: 0})
                this.setData({placeActions: groups})
            }
        });
    },

    saveRecord(){
        const {tempFormData} = this.data;
        if (!tempFormData?.flag) {
            wx.$http.post({url: '/szm/icpwdrecord', data: Object.assign(tempFormData, userIdParam())}).then(res => {
                tempFormData.flag = 1;
            });
        }
    },
    tapLogin: function() {
        wx.navigateTo({
          url: '../login/index',
        })
      },

      bindSwiperChange(e) {
        if(wx.$wechatLogin.state === "pending") {
          return;
        }
        const {current, source} = e.detail;
        const activeTabIndex = parseInt(current);
        if(activeTabIndex === 0) {
          this.initEdun();
        } else if(activeTabIndex === 1){
          this.initCloud();
        }
        this.setData({activeTabIndex})
    },

    
})